package agent_store

import (
	"context"
	"encoding/json"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type TotalSalesDetailsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewTotalSalesDetailsLogic(ctx context.Context, svcCtx *svc.ServiceContext) TotalSalesDetailsLogic {
	return TotalSalesDetailsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *TotalSalesDetailsLogic) TotalSalesDetails(req *types.TotalSalesDetailsReq) (resp *types.TotalSalesDetailsResp, err error) {
	agentId, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return nil, err
	}
	storeList, err := l.svcCtx.AgentRpc.StoreList(l.ctx, &agentClient.StoreListReq{
		Page:            1,
		PageSize:        1000,
		Status:          -1,
		Platform:        "xiuxian",
		AgentId:         agentId,
		SelectFirstPass: true,
	})
	if err != nil {
		return nil, err
	}

	ids := make([]string, 0)
	for _, store := range storeList.List {
		ids = append(ids, respx.IDFrom(store.StoreId).ToString())
	}

	reqParam := TotalSalesDetailsReq{
		Ids: ids,
	}

	reqStr, err := json.Marshal(reqParam)
	if err != nil {
		return nil, err
	}
	bytes, err := tools.RequestOtherPlatform(
		l.svcCtx.Config.XiuXianApi.TotalSalesDetails,
		"POST",
		l.svcCtx.Config.Auth.AccessSecret,
		string(reqStr),
		l.svcCtx.Config.Auth.AccessExpire,
		10000, // admin_users表 下楼系统账户的ID
	)
	if err != nil {
		return nil, err
	}

	var res TotalSalesDetailsResp
	err = json.Unmarshal(bytes, &res)
	if err != nil {
		logx.Infof("调用%v商家销售明细接口err：%v", req.Platform, err.Error())
		return nil, errorx.NewMsgReasonCodeError(errorx.DefaultCode, "调用商家销售明细接口err：%v", err.Error())
	}

	logx.Infof("商家销售明细: %v", res)
	if res.Code != 200 {
		return nil, errorx.NewCodeReason(res.Code, res.Message)
	}

	return &res.Data, nil
}

type TotalSalesDetailsReq struct {
	Ids []string `json:"ids"`
}

type TotalSalesDetailsResp struct {
	Code    int                         `json:"code"`
	Message string                      `json:"message"`
	Data    types.TotalSalesDetailsResp `json:"data"`
}
